import React, { useEffect, useRef } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';
import { Spin } from 'antd';

interface ProtectedRouteProps {
  children: React.ReactNode;
  requireAdmin?: boolean;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ 
  children, 
  requireAdmin = false 
}) => {
  const { isAuthenticated, user, isLoading } = useAuthStore();
  const location = useLocation();
  const redirecting = useRef(false);
  const hasCheckedAuth = useRef(false);
  const redirectCount = useRef(0);

  // 调试日志
  useEffect(() => {
    console.log('ProtectedRoute检查状态:', {
      isAuthenticated,
      isLoading,
      user: !!user,
      pathname: location.pathname
    });
  }, [isAuthenticated, isLoading, user, location.pathname]);

  // 检测重定向循环
  useEffect(() => {
    // 检查 sessionStorage 中的重定向计数
    const storedCount = sessionStorage.getItem('redirectCount');
    if (storedCount) {
      redirectCount.current = parseInt(storedCount, 10);
    }
    
    // 如果重定向次数过多，可能是循环
    if (redirectCount.current > 5) {
      console.warn('检测到可能的重定向循环，重置计数器');
      sessionStorage.removeItem('redirectCount');
      redirectCount.current = 0;
    }
  }, []);

  // 如果正在加载，显示加载状态
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000'
      }}>
        <Spin size="large" />
      </div>
    );
  }

  // 如果未认证，重定向到登录页
  if (!hasCheckedAuth.current && !redirecting.current && !isAuthenticated) {
    console.log('用户未认证，重定向到登录页');
    hasCheckedAuth.current = true;
    redirecting.current = true;
    
    // 增加重定向计数
    redirectCount.current += 1;
    sessionStorage.setItem('redirectCount', redirectCount.current.toString());
    
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 如果需要管理员权限但用户不是管理员，重定向到首页
  if (!hasCheckedAuth.current && !redirecting.current && requireAdmin && user && !user.is_superuser) {
    console.log('需要管理员权限但用户不是管理员，重定向到首页');
    hasCheckedAuth.current = true;
    redirecting.current = true;
    
    // 增加重定向计数
    redirectCount.current += 1;
    sessionStorage.setItem('redirectCount', redirectCount.current.toString());
    
    return <Navigate to="/dashboard" replace />;
  }

  // 重置重定向计数（成功渲染受保护内容）
  useEffect(() => {
    if (isAuthenticated && !redirecting.current) {
      sessionStorage.removeItem('redirectCount');
      redirectCount.current = 0;
    }
  }, [isAuthenticated]);

  hasCheckedAuth.current = true;
  return <>{children}</>;
};

export default ProtectedRoute;